﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Metrics;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kang.Monitor.Wpf.Service
{
    public class ModbusHelp : IDisposable
    {
        private static SerialPort serialPort = null;
        private Modbus.Device.IModbusSerialMaster master = null;

        public ModbusHelp()
        {
            serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
        }

        public void Dispose()
        {
            master?.Dispose();
            serialPort?.Close();
        }

        public void DoModbus(Action<ushort[]> action)
        {
            #region Modbus通信

            Task.Run(async () =>
            {
                try
                {
                    if (!serialPort.IsOpen)
                    {
                        serialPort.Open();
                    }
                    if (master == null)
                    {
                        master = Modbus.Device.ModbusSerialMaster.CreateRtu(serialPort);
                    }
                    while (true)
                    {
                        await Task.Delay(500);
                        ushort[] values = master.ReadHoldingRegisters(1, 0, 4);
                        action?.Invoke(values);
                    }
                }
                catch (Exception)
                {
                }
                finally
                {
                    master?.Dispose();
                    serialPort?.Close();
                }
            }
                );

            #endregion Modbus通信
        }

        public void SendMsgModbus(ushort value)
        {
            Task.Run(async () =>
            {
                try
                {
                    if (!serialPort.IsOpen)
                    {
                        serialPort.Open();
                    }
                    if (master == null)
                    {
                        master = Modbus.Device.ModbusSerialMaster.CreateRtu(serialPort);
                    }

                    master.WriteSingleRegister(1, 0, value);
                }
                catch (Exception)
                {
                    master?.Dispose();
                    serialPort?.Close();
                }
                finally
                {
                }
            }
                );
        }
    }
}